<template>
    <div class="friends-container">
        <!-- 左侧好友列表 -->
        <div class="friends-panel">
            <div class="panel-header">
                <h2>我的好友</h2>
                <div class="search-container">
                    <el-input 
                        v-model="searchFriend" 
                        placeholder="搜索好友" 
                        prefix-icon="el-icon-search"
                        clearable
                        @clear="getFriendList"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="searchFriends"></el-button>
                    </el-input>
                </div>
            </div>
            
            <div class="friends-list">
                <div v-if="friendList.length === 0" class="empty-list">
                    <i class="el-icon-user"></i>
                    <p>暂无好友或未找到相关好友</p>
                </div>
                
                <div v-for="(item, index) in friendList" :key="index" class="friend-card">
                    <div class="friend-info">
                        <el-avatar :size="50" :src="item.userPicture" class="friend-avatar"></el-avatar>
                        <div class="friend-details">
                            <div class="friend-name">
                                {{ item.userName }}
                                <span class="user-rank" :class="getRankClass(item.userRank)">
                                    {{ getRankLabel(item.userRank) }}
                                </span>
                            </div>
                            <div class="friend-email">{{ item.userEmail }}</div>
                        </div>
                    </div>
                    <div class="friend-actions">
                        <el-button 
                            type="danger" 
                            size="mini" 
                            icon="el-icon-delete" 
                            circle
                            @click="removeFriend(item.userEmail, index)"
                            title="删除好友"
                        ></el-button>
                        <el-button 
                            type="primary" 
                            size="mini" 
                            icon="el-icon-chat-dot-round" 
                            circle
                            @click="chatWithFriend(item.userEmail)"
                            title="发消息"
                        ></el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧添加好友和请求面板 -->
        <div class="right-panels">
            <!-- 添加好友面板 -->
            <div class="add-friend-panel">
                <div class="panel-header">
                    <h2>添加好友</h2>
                    <div class="search-container">
                        <el-input 
                            v-model="searchAdded" 
                            placeholder="输入邮箱查找用户" 
                            prefix-icon="el-icon-user-solid"
                            clearable
                        >
                            <el-button slot="append" icon="el-icon-search" @click="searchUsers"></el-button>
                        </el-input>
                    </div>
                </div>

                <div class="user-search-results">
                    <div v-if="userList.length === 0" class="empty-list">
                        <i class="el-icon-search"></i>
                        <p>搜索用户以添加好友</p>
                    </div>
                    
                    <div v-for="(item, index) in userList" :key="index" class="user-card">
                        <div class="user-info">
                            <el-avatar :size="50" :src="item.userPicture" class="user-avatar"></el-avatar>
                            <div class="user-details">
                                <div class="user-name">
                                    {{ item.userName }}
                                    <span class="user-rank" :class="getRankClass(item.userRank)">
                                        {{ getRankLabel(item.userRank) }}
                                    </span>
                                </div>
                                <div class="user-email">{{ item.userEmail }}</div>
                            </div>
                        </div>
                        <el-button 
                            type="success" 
                            size="small" 
                            icon="el-icon-plus" 
                            @click="addFriendRequest(item.userEmail)"
                        >添加</el-button>
                    </div>
                </div>
            </div>

            <!-- 好友请求面板 -->
            <div class="friend-request-panel">
                <div class="panel-header">
                    <h2>好友申请</h2>
                    <el-badge :value="friendRequest.length" :hidden="friendRequest.length === 0" class="request-badge">
                        <i class="el-icon-bell"></i>
                    </el-badge>
                </div>
                
                <div class="request-list">
                    <div v-if="friendRequest.length === 0" class="empty-list">
                        <i class="el-icon-message"></i>
                        <p>暂无好友申请</p>
                    </div>
                    
                    <div v-for="(item, index) in friendRequest" :key="index" class="request-card">
                        <div class="request-info">
                            <el-avatar :size="50" :src="item.userPicture" class="friend-avatar"></el-avatar>
                            <div class="request-user">
                                <div class="user-name">
                                    {{ item.userName }}
                                    <span class="user-rank" :class="getRankClass(item.userRank)">
                                        {{ getRankLabel(item.userRank) }}
                                    </span>
                                </div>
                                <div class="request-message">"{{ item.requestText }}"</div>
                            </div>
                        </div>
                        <div class="request-actions">
                            <el-button 
                                type="success" 
                                size="mini" 
                                icon="el-icon-check" 
                                @click="agree(item.userEmail, index)"
                            >同意</el-button>
                            <el-button 
                                type="danger" 
                                size="mini" 
                                icon="el-icon-close" 
                                @click="disagree(item.userEmail, index)"
                            >拒绝</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {
    getFriendList,
    getUserFriendList,
    findFriendByEmail,
    addFriend,
    removeFriend,
    getMyFriendResponse, deleteFriendRequest, addFriendRequest
} from "@/api/api";
import { getRankClass, getRankLabel } from "@/utils/rankUtils";

export default {
    created() {
        this.getFriendList();
        this.getFriendRequest();
    },
    data() {
        return {
            friendRequest: [],
            searchFriend: '', // 搜索好友的输入框值
            searchAdded: '', // 添加好友的输入框值
            active: 0,
            friendList: [],
            userList: [],
        };
    },
    methods: {
        getRankClass,
        getRankLabel,
        async searchFriends() {
            if (!this.searchFriend.trim()) {
                await this.getFriendList();
                return;
            }
            
            try {
                const response = await findFriendByEmail({
                    params: {
                        userEmail: this.searchFriend
                    },
                });
                if (response && response.data && response.data.message === "成功") {
                    this.friendList = [response.data.data]; // 假设返回的是单个对象
                } else {
                    this.$message.warning("未找到好友");
                    // 保持现有列表不变
                }
            } catch (error) {
                this.$message.error('搜索好友失败！');
                console.error(error);
            }
        },
        
        async searchUsers() {
            if (!this.searchAdded.trim()) {
                this.userList = [];
                return;
            }
            
            // 判断是否在搜索自己
            if (this.searchAdded === this.$store.state.me.userEmail) {
                this.$message.warning("不能添加自己为好友");
                this.userList = [];
                return;
            }
            
            try {
                const response = await getUserFriendList({
                    params: {
                        userEmail: this.searchAdded
                    },
                });
                if (response && response.data && response.data.message === "成功") {
                    this.userList = [response.data.data]; // 假设返回的是单个对象
                } else {
                    this.$message.warning("未找到用户");
                    this.userList = [];
                }
            } catch (error) {
                this.$message.error('搜索用户失败！');
                console.error(error);
            }
        },
        
        async getFriendList() {
            try {
                const response = await getFriendList();
                if (response && response.data && response.data.message === "成功") {
                    this.friendList = response.data.data;
                } else {
                    this.$message.error("好友列表加载失败");
                }
            } catch (e) {
                this.$message.error('加载好友列表失败！');
                console.error(e);
            }
        },
        
        async removeFriend(friend, index) {
            try {
                this.$confirm('确定要删除该好友吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const response = await removeFriend({
                        params: {
                            friendEmail: friend
                        },
                    });
                    if (response && response.data && response.data.message === "成功") {
                        this.$message.success('删除成功');
                        this.friendList.splice(index, 1);
                    } else {
                        this.$message.error("删除失败：" + response.data.message);
                    }
                }).catch(() => {
                    // 用户取消删除操作
                });
            } catch (error) {
                this.$message.error('删除好友失败！');
                console.error(error);
            }
        },
        
        async chatWithFriend(email) {
            try {
                // 查找好友的完整信息
                const response = await findFriendByEmail({
                    params: {
                        userEmail: email
                    },
                });
                
                if (response && response.data && response.data.message === "成功") {
                    const friendInfo = response.data.data;
                    this.$message.success('正在打开与 ' + friendInfo.userName + ' 的聊天');
                    // 跳转到私聊页面，并传递好友信息
                    this.$router.push({ 
                        path: '/Main/privateChat/chat', 
                        query: { count: friendInfo } 
                    });
                } else {
                    this.$message.error("获取好友信息失败");
                }
            } catch (error) {
                this.$message.error('打开聊天窗口失败！');
                console.error(error);
            }
        },
        
        async addFriend(email) {
            try {
                const response = await addFriend({
                    friendEmail: email
                });
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success('添加好友成功');
                    // 刷新好友列表
                    await this.getFriendList();
                    // 从userList中移除已添加的用户
                    this.userList = this.userList.filter(user => user.userEmail !== email);
                } else {
                    this.$message.error("添加好友失败");
                }
            } catch (error) {
                this.$message.error('添加好友失败！');
                console.error(error);
            }
        },
        
        async agree(email, index) {
            try {
                this.friendRequest.splice(index, 1);
                await this.addFriend(email);
                const response = await deleteFriendRequest(email);
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success("已同意好友请求");
                } else {
                    this.$message.error("处理好友请求失败");
                }
            } catch (error) {
                this.$message.error('处理好友请求失败！');
                console.error(error);
            }
        },
        
        async disagree(email, index) {
            try {
                this.friendRequest.splice(index, 1);
                const response = await deleteFriendRequest(email);
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success("已拒绝好友请求");
                } else {
                    this.$message.error("处理好友请求失败");
                }
            } catch (error) {
                this.$message.error('处理好友请求失败！');
                console.error(error);
            }
        },
        
        async getFriendRequest() {
            try {
                const response = await getMyFriendResponse();
                if (response && response.data && response.data.message === "成功") {
                    this.friendRequest = response.data.data;
                } else {
                    this.$message.error("好友请求列表加载失败");
                }
            } catch (error) {
                this.$message.error('加载好友请求失败！');
                console.error(error);
            }
        },
        
        async addFriendRequest(userEmail) {
            // 再次确认不是添加自己为好友
            if (userEmail === this.$store.state.me.userEmail) {
                this.$message.warning("不能添加自己为好友");
                return;
            }
            
            try {
                const response = await addFriendRequest({
                    anotherUserEmail: userEmail,
                    text: "你好，我想添加你为好友"
                });
                if (response && response.data && response.data.message === "成功") {
                    this.$message.success('已发送好友请求');
                    // 清空搜索结果
                    this.searchAdded = '';
                    this.userList = [];
                } else {
                    this.$message.error("发送好友请求失败");
                }
            } catch (error) {
                this.$message.error('发送好友请求失败！');
                console.error(error);
            }
        }
    },
};
</script>

<style scoped>
.friends-container {
    display: flex;
    padding: 20px;
    gap: 20px;
    height: calc(100vh - 120px);
    background-color: #f5f7fa;
}

/* 左侧好友列表面板 */
.friends-panel {
    flex: 1.5;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 右侧面板容器 */
.right-panels {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* 添加好友面板 */
.add-friend-panel {
    flex: 1;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 好友请求面板 */
.friend-request-panel {
    flex: 1;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

/* 面板头部 */
.panel-header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.panel-header h2 {
    margin: 0;
    font-size: 18px;
    color: #303133;
    font-weight: 600;
}

/* 搜索容器 */
.search-container {
    width: 70%;
    max-width: 350px;
}

/* 好友列表容器 */
.friends-list,
.user-search-results,
.request-list {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
}

/* 滚动条样式 */
.friends-list::-webkit-scrollbar,
.user-search-results::-webkit-scrollbar,
.request-list::-webkit-scrollbar {
    width: 6px;
}

.friends-list::-webkit-scrollbar-track,
.user-search-results::-webkit-scrollbar-track,
.request-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.friends-list::-webkit-scrollbar-thumb,
.user-search-results::-webkit-scrollbar-thumb,
.request-list::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 3px;
}

.friends-list::-webkit-scrollbar-thumb:hover,
.user-search-results::-webkit-scrollbar-thumb:hover,
.request-list::-webkit-scrollbar-thumb:hover {
    background: #c0c4cc;
}

/* 好友卡片 */
.friend-card,
.user-card,
.request-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    margin-bottom: 10px;
    background-color: #f9f9f9;
    border-radius: 8px;
    transition: all 0.3s;
}

.friend-card:hover,
.user-card:hover,
.request-card:hover {
    background-color: #ecf5ff;
    transform: translateY(-2px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 好友信息 */
.friend-info,
.user-info,
.request-info {
    display: flex;
    align-items: center;
}

.friend-avatar,
.user-avatar {
    margin-right: 15px;
    border: 2px solid #e8f4ff;
}

.friend-details,
.user-details,
.request-user {
    display: flex;
    flex-direction: column;
}

.friend-name,
.user-name {
    font-weight: 500;
    font-size: 16px;
    color: #303133;
    margin-bottom: 4px;
}

.friend-email,
.user-email {
    font-size: 13px;
    color: #909399;
}

.request-message {
    font-size: 14px;
    color: #606266;
    font-style: italic;
    margin-top: 5px;
}

/* 操作按钮 */
.friend-actions,
.request-actions {
    display: flex;
    gap: 10px;
}

/* 空白列表提示 */
.empty-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #909399;
}

.empty-list i {
    font-size: 48px;
    margin-bottom: 10px;
    color: #dcdfe6;
}

.empty-list p {
    margin: 0;
    font-size: 14px;
}

/* 请求计数徽章 */
.request-badge {
    margin-left: 15px;
}

.request-badge i {
    font-size: 22px;
    color: #909399;
}

/* 用户等级样式 */
.user-rank {
    display: inline-block;
    font-size: 11px;
    font-weight: bold;
    padding: 1px 5px;
    border-radius: 3px;
    margin-left: 4px;
    color: white;
    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
    vertical-align: middle;
}

.rank-d {
    background: linear-gradient(135deg, #4caf50, #2e7d32);
}

.rank-c {
    background: linear-gradient(135deg, #2196f3, #0d47a1);
}

.rank-b {
    background: linear-gradient(135deg, #9c27b0, #4a148c);
}

.rank-a {
    background: linear-gradient(135deg, #424242, #212121);
}

.rank-a-plus {
    background: linear-gradient(135deg, #ff9800, #e65100);
}

.rank-s {
    background: linear-gradient(135deg, #ffd700, #ff6f00);
    color: #5d4037;
}
</style>
